package com.sjz.han.industry.fragments;

import android.Manifest;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.sjz.han.industry.R;
import com.sjz.han.industry.activites.AlterPwdActivity;
import com.sjz.han.industry.activites.KeFuActivity;
import com.sjz.han.industry.activites.LoginActivity;
import com.sjz.han.industry.activites.MyYqmActivity;
import com.sjz.han.industry.activites.PersonMsgActivity;
import com.sjz.han.industry.activites.PersonMsgEditActivity;
import com.sjz.han.industry.activites.UploadPayMsgActivity;
import com.sjz.han.industry.activites.WaitJhMemberActivity;
import com.sjz.han.industry.activites.WaitSettlementMemberActivity;
import com.sjz.han.industry.base.BaseFragment;
import com.sjz.han.industry.entities.LoignEntity;
import com.sjz.han.industry.entities.PersonEntity;
import com.sjz.han.industry.internetmanage.ReqestUrl;
import com.sjz.han.industry.utils.GlideImageLoader;
import com.sjz.han.industry.utils.JsonUtils;
import com.sjz.han.industry.utils.PicUtils;
import com.sjz.han.industry.utils.ToastUtils;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 我的
 */
public class MineFragment extends BaseFragment implements View.OnClickListener{

    private ImageView mine_photo_img;//头像
    private LinearLayout mine_C2part_ll;//c2角色展示
    private RelativeLayout mine_GRZL_rel,mine_PWD_rel,mine_KF_rel,mine_wdyqm_rel,mine_DJHCY_rel,mine_DJSUAN_rel,mine_EXIT_tv;

    private TextView mine_JHHY_tv;//激活会员
    private String jhStatus="";
    private TextView mine_name_tv,mine_hybh_tv,mine_zcsj_tv;//
    private String yqmStr="";
    @Override
    protected int setLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initViews() {
        mine_JHHY_tv=(TextView)getView().findViewById(R.id.mine_JHHY_tv);
        mine_name_tv=(TextView)getView().findViewById(R.id.mine_name_tv);
        mine_hybh_tv=(TextView)getView().findViewById(R.id.mine_hybh_tv);
        mine_zcsj_tv=(TextView)getView().findViewById(R.id.mine_zcsj_tv);

        mine_GRZL_rel=(RelativeLayout)getView().findViewById(R.id.mine_GRZL_rel);
        mine_PWD_rel=(RelativeLayout)getView().findViewById(R.id.mine_PWD_rel);
        mine_KF_rel=(RelativeLayout)getView().findViewById(R.id.mine_KF_rel);
        mine_wdyqm_rel=(RelativeLayout)getView().findViewById(R.id.mine_wdyqm_rel);
        mine_DJHCY_rel=(RelativeLayout)getView().findViewById(R.id.mine_DJHCY_rel);
        mine_DJSUAN_rel=(RelativeLayout)getView().findViewById(R.id.mine_DJSUAN_rel);//待结算会员
        mine_EXIT_tv=(RelativeLayout)getView().findViewById(R.id.mine_EXIT_tv);

        mine_C2part_ll=(LinearLayout)getView().findViewById(R.id.mine_C2part_ll);

        mine_photo_img=(ImageView)getView().findViewById(R.id.mine_photo_img);
    }

    @Override
    protected void initDatas() {
        if("5".equals(shareUtils.getLevel())){
            mine_C2part_ll.setVisibility(View.VISIBLE);
        }else{
            mine_C2part_ll.setVisibility(View.GONE);
        }
    }

    @Override
    protected void setLisener() {
        mine_JHHY_tv.setOnClickListener(this);
        mine_name_tv.setOnClickListener(this);
        mine_EXIT_tv.setOnClickListener(this);

        mine_GRZL_rel.setOnClickListener(this);
        mine_PWD_rel.setOnClickListener(this);
        mine_KF_rel.setOnClickListener(this);
        mine_wdyqm_rel.setOnClickListener(this);
        mine_DJHCY_rel.setOnClickListener(this);
        mine_photo_img.setOnClickListener(this);
        mine_DJSUAN_rel.setOnClickListener(this);
    }

    @Override
    protected void onRetry() {

    }

    @Override
    public void onClick(View v) {
     switch (v.getId()){
         case R.id.mine_JHHY_tv://激活会员
             if("0".equals(jhStatus)){
                 startActivity(new Intent(activity, UploadPayMsgActivity.class));
             }else{

             }

             break;

         case R.id.mine_name_tv:
             startActivity(new Intent(activity, PersonMsgEditActivity.class));
             break;
         case R.id.mine_wdyqm_rel:
             startActivity(new Intent(activity, MyYqmActivity.class).putExtra("YQM",yqmStr));
             break;
         case R.id.mine_KF_rel:
             startActivity(new Intent(activity, KeFuActivity.class));
             break;
         case R.id.mine_GRZL_rel:
             startActivity(new Intent(activity, PersonMsgEditActivity.class));
             break;
         case R.id.mine_DJHCY_rel://待激活成员
             startActivity(new Intent(activity, WaitJhMemberActivity.class));
             break;
         case R.id.mine_DJSUAN_rel://待结算
             startActivity(new Intent(activity, WaitSettlementMemberActivity.class));
             break;
         case R.id.mine_PWD_rel://密码管理
             startActivity(new Intent(activity, AlterPwdActivity.class));
             break;
         case R.id.mine_EXIT_tv://安全退出
             shareUtils.clearUserInfo();
             startActivity(new Intent(activity, LoginActivity.class));
             activity.finish();
             break;
         case R.id.mine_photo_img://头像
             //头像
             PermissionsUtil.requestPermission(activity, new PermissionListener() {
                 @Override
                 public void permissionGranted(@NonNull String[] permission) {
                     List<String> pathList = new ArrayList<>();

                     GalleryConfig galleryConfig = new GalleryConfig.Builder()
                             .imageLoader(new GlideImageLoader())
                             .iHandlerCallBack(iHandlerCallBack)
                             .provider("com.sjz.han.industry.fileprovider")
                             .pathList(pathList)
                             .multiSelect(false)
                             .multiSelect(false, 1)
                             .maxSize(1)
                             .crop(true)// 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                             .crop(true, 1, 1, 500, 500) // 配置裁剪功能的参数，   默认裁剪比例 1:1
                             .isShowCamera(true)
                             .filePath("/zijinpans")
                             .build();

                     GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(activity);
                 }

                 @Override
                 public void permissionDenied(@NonNull String[] permission) {

                 }
             }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                     Manifest.permission.READ_EXTERNAL_STORAGE,
                     Manifest.permission.CAMERA,
                     Manifest.permission.RECORD_AUDIO});
             break;
     }
    }
    IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
        @Override
        public void onStart() {
        }

        @Override
        public void onSuccess(List<String> photoList) {
            File file = new File(photoList.get(0));
            yasuoimg(file,photoList.get(0));

        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onFinish() {
        }

        @Override
        public void onError() {
        }
    };
    //压缩图片
    public void yasuoimg(File photos, final String imgpaht){
        Luban.with(activity)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        showLoadingDialog("正在压缩图片...");
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        hideLoadingDialog();
                        uploadPhoto(file,imgpaht);
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        hideLoadingDialog();
                    }
                }).launch();
    }
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/zijinpanhuo/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }
    /**
     * 上传照片
     */
    public void uploadPhoto(final File file, final String imgpaht) {
        showLoadingDialog("正在上传头像...");
        //图片参数，图片名称，图片文件
        final PostFormBuilder builder = OkHttpUtils.post().url(ReqestUrl.PHOTO_UPLOAD_URL);
        if (!file.exists()) {
            return;
        }
        String filename = file.getName();
        builder.addFile("file", filename, file);
        builder.addParams("token",shareUtils.getToken());
        builder.build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        hideLoadingDialog();
                        ToastUtils.popUpToast("提交失败,请稍后重试!");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideLoadingDialog();
                        if(ReqestUrl.rebacRequestJson(response)!=null){
                            LoignEntity entity= JsonUtils.getObject(response,LoignEntity.class);
                            if(entity!=null&&entity.code==0){
                               PicUtils.showImageViewToCircle(activity, R.mipmap.ic_wd_tx, imgpaht, mine_photo_img);
                                ToastUtils.popUpToast(entity.msg);
                            }else{
                                ToastUtils.popUpToast(entity.msg);
                            }
                        }

                    }
                });
    }
    @Override
    public void onResume() {
        super.onResume();
     getMsg();

    }

    public void getMsg(){
        OkHttpUtils
                .post()
                .url(ReqestUrl.PERSONMSG_URL)
                .addParams("token",shareUtils.getToken())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.popUpToast("请求超时");
            }
            @Override
            public void onResponse(String response, int id) {
                if(ReqestUrl.rebacRequestJson(response)!=null){
                    PersonEntity entity= JsonUtils.getObject(response,PersonEntity.class);
                    if(entity!=null){
                         if(entity.code==0){
                             if(entity.data!=null){
                                 shareUtils.setYQM(entity.data.inviteCode);
                                 shareUtils.setLevel(entity.data.level);
                                 yqmStr=entity.data.inviteCode;
                                 shareUtils.setUserPhoto(entity.data.photo);
                                 shareUtils.setUserName(entity.data.username);
                                 jhStatus=entity.data.status;
                                 shareUtils.setJhStatus(jhStatus);
                                 if("0".equals(jhStatus)){
                                     mine_JHHY_tv.setText("待激活");
                                     mine_JHHY_tv.setTextColor(ContextCompat.getColor(activity,R.color.tv_color16));
                                 }else{
                                     mine_JHHY_tv.setText("已激活");
                                     mine_JHHY_tv.setTextColor(ContextCompat.getColor(activity,R.color.common_color));
                                 }
                                 mine_name_tv.setText(entity.data.username);
                                 mine_hybh_tv.setText("会员编号："+entity.data.userId);
                                 mine_zcsj_tv.setText("注册时间："+entity.data.excelCreateTime);
                                 PicUtils.showImageViewToCircle(activity, R.mipmap.ic_wd_tx, ReqestUrl.BASE+entity.data.photo, mine_photo_img);
                             }
                         }else if(entity.code==301){
                             startActivity(new Intent(activity,LoginActivity.class));
                             activity.finish();
                         }

                    }else{
                        ToastUtils.popUpToast(entity.msg);
                    }
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }
}
